<?php

namespace App\Http\Controllers;

use App\Models\Posts;

class PostController extends Controller
{
    //文章列表
    public function index()
    {
        $posts = Posts::orderBy('created_at', 'desc')->paginate(10);
        return view("posts/index", compact('posts'));
    }
    //显示文章
    public function show(Posts $post)
    {
        return view("posts/show", compact( 'post'));
    }
    //添加文章
    public function create()
    {
        return view("posts/create");
    }
    //添加文章
    public function store()
    {
        $this->validate(request(),[
            'title'=>"required|string|max:100|min:5",
            'content'=>"required|string|min:10"
        ]);

        Posts::create(\request(['title', 'content']));
        return redirect('/posts');
    }
    //编辑文章
    public function edit(Posts $post)
    {
        return view("posts/edit",compact( 'post'));
    }
    //修改文章
    public function update(Posts $post)
    {
        $this->validate(request(),[
            'title'=>"required|string|max:100|min:5",
            'content'=>"required|string|min:10"
        ]);

        $post->title = request('title');
        $post->content = request('content');
        $post->save();
        return redirect('/posts/'.$post->id);
    }
    //删除文章
    public function delete(Posts $post)
    {
        if($post->delete()){
            return redirect('/posts');
        }else{
            echo "删除文章失败";
        }

    }
}
